package com.wm.yigongfang.common.jwt;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wm.yigongfang.common.config.ServiceException;
import com.wm.yigongfang.common.web.Result;
import com.wm.yigongfang.dao.AdminDao;
import com.wm.yigongfang.dao.UserDao;
import com.wm.yigongfang.entity.Admin;
import com.wm.yigongfang.entity.User;
import com.wm.yigongfang.enums.PlatEnums;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author zp
 * @version 1.0
 * @date 2021/5/2 0:06
 */
public class AuthenticationInterceptor implements HandlerInterceptor{
    @Autowired
    UserDao userDao;
    @Autowired
    AdminDao adminDao;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        // 检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                UserContext userContext = new UserContext();
                // 执行认证
                if (token == null) {
                    throw new ServiceException("无token，请重新登录");
                }
                // 获取 token 中的 user id
                String wxOpenID = null;
                try {
                    DecodedJWT jwt = JWT.decode(token);
                    wxOpenID = jwt.getIssuer();
                } catch (JWTDecodeException j) {
                    resultFail(httpServletResponse);
                    return false;
                }
                if (wxOpenID == null) {
                    resultFail(httpServletResponse);
                    return false;
                }
                // 从 http 请求头中取出 plat
                String plat = httpServletRequest.getHeader("plat");
                if (plat == null) {
                    throw new ServiceException("错误的平台类型");
                }
                if (plat.equals(PlatEnums.APP.desc)) {
                    User user = userDao.findByWXOpenid(wxOpenID);
                    if (user == null) {
                        resultFail(httpServletResponse);
                        return false;
                    }
                }else if (plat.equals(PlatEnums.CMS.desc)){
                    //TODO:::
                    Admin admin = adminDao.getById(wxOpenID);
                    if (admin == null) {
                        resultFail(httpServletResponse);
                        return false;
                    }
                    userContext.setRole(admin.getRole());
                }else {
                    throw new ServiceException("错误的平台类型");
                }
                userContext.setWxOpenID(wxOpenID);
                userContext.setLanguage(httpServletRequest.getHeader("language"));
                UserContextHolder.set(userContext);
                return true;
            }
        }
        return true;
    }

    private void resultFail(HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.setStatus(HttpStatus.OK.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setLocale(new java.util.Locale("zh", "CN"));
        httpServletResponse.getWriter().write(JSONUtil.toJsonStr(new Result(401, "身份验证失败，请重新登录", null)));
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
